package frames;

import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.DefaultFontMapper;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileOutputStream;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.ArrayList;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import model.Historico;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import reportesdeer.IReportes;
import reportesdeer.PropiedadesReportes;
import reportesdeer.Reportes;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Rossy
 */
public class Reporte2 extends javax.swing.JFrame {

    /**
     * Creates new form Reporte2
     */
    
    String port;
    String server;
    Properties reportesPropiedades;
    
    public Reporte2() {
//        inicializar();
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        cmbRango = new javax.swing.JComboBox();
        btnGenerar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        cmbDia = new javax.swing.JComboBox();
        btnGuardar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Cantidad de zonas más rankeadas :");

        cmbRango.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "5", "10", "15", "20", "25", "30", "35", "40", "45", "50" }));

        btnGenerar.setText("Generar");
        btnGenerar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGenerarActionPerformed(evt);
            }
        });

        jLabel2.setText("Día de la semana :");

        cmbDia.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "lunes", "martes", "miercoles", "jueves", "viernes", "sabado", "domingo" }));

        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(114, 114, 114))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnGenerar)
                                .addGap(18, 18, 18)))
                        .addComponent(btnGuardar))
                    .addComponent(cmbDia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmbRango, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cmbRango, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cmbDia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnGenerar)
                    .addComponent(btnGuardar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGenerarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGenerarActionPerformed
        try {        
            String strRango=this.cmbRango.getSelectedItem().toString();
            String strDia=this.cmbDia.getSelectedItem().toString();
            ArrayList<Historico>historicoList=new ArrayList<Historico>();
            ArrayList<Historico>historicoOrdenado=new ArrayList<Historico>();
            int rango=Integer.parseInt(strRango);
            
            Reportes dao=new Reportes();
            historicoList=dao.generarReporte2(strDia);
            
//            Registry reg = LocateRegistry.getRegistry(port, 1099);
//            IReportes rmi = (IReportes)reg.lookup(server);
//            historicoList=rmi.generarReporte2(strDia);
//            
            for(int i=0;i<rango;i++){
                int a=historicoList.get(rango-i-1).getId();
                int b=historicoList.get(rango-i-1).getCant();
                Historico historico=new Historico();
                historico.setId(a);
                historico.setCant(b);
                historicoOrdenado.add(historico);
            }
            DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
            
            for (int i=0;i<historicoOrdenado.size();i++){
                dataSet.setValue(historicoOrdenado.get(i).getId(), ""+historicoOrdenado.get(i).getId(),""+historicoOrdenado.get(i).getCant());
            }
            
            JFreeChart chart = ChartFactory.createBarChart("Ranking de las zonas más congestionadas", "Cantidad de Vehículos", "Zona", dataSet, PlotOrientation.VERTICAL,true , true, true);
            CategoryPlot plot = chart.getCategoryPlot();
            plot.setRangeGridlinePaint(Color.BLACK);
            
            BarRenderer renderer= (BarRenderer) plot.getRenderer();
            renderer.setDrawBarOutline(false);
            //Dar color a cada barra
            GradientPaint gp0= new GradientPaint(0.0f,0.0f,Color.MAGENTA,0.0f,0.0f,new Color(0,0,64));
            renderer.setSeriesPaint(0,gp0);
            
            ChartFrame frame=new ChartFrame("Reporte 2",chart);
            frame.setVisible(true);
            frame.setSize(800,500);
//            writeChartToPDF(chart, 800, 500, "Reporte2.pdf");
        } catch (RemoteException ex) {
            Logger.getLogger(Reporte2.class.getName()).log(Level.SEVERE, null, ex);
        } 
        
    }//GEN-LAST:event_btnGenerarActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        try {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setAcceptAllFileFilterUsed(false);
            FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF files", "pdf");
            fileChooser.addChoosableFileFilter(filter);
            fileChooser.showSaveDialog(null);
            File file = fileChooser.getSelectedFile();
            String filename = file.getAbsolutePath();
            
            String strRango=this.cmbRango.getSelectedItem().toString();
            String strDia=this.cmbDia.getSelectedItem().toString();
            ArrayList<Historico>historicoList=new ArrayList<Historico>();
            ArrayList<Historico>historicoOrdenado=new ArrayList<Historico>();
            int rango=Integer.parseInt(strRango);

            Reportes dao=new Reportes();
            historicoList=dao.generarReporte2(strDia);
            
//            Registry reg = LocateRegistry.getRegistry(port, 1099);
//            IReportes rmi = (IReportes)reg.lookup(server);
//            historicoList=rmi.generarReporte2(strDia);

            for(int i=0;i<rango;i++){
                int a=historicoList.get(rango-i-1).getId();
                int b=historicoList.get(rango-i-1).getCant();
                Historico historico=new Historico();
                historico.setId(a);
                historico.setCant(b);
                historicoOrdenado.add(historico);
            }
            DefaultCategoryDataset dataSet = new DefaultCategoryDataset();

            for (int i=0;i<historicoOrdenado.size();i++){
                dataSet.setValue(historicoOrdenado.get(i).getId(), ""+historicoOrdenado.get(i).getId(),""+historicoOrdenado.get(i).getCant());
            }

            JFreeChart chart = ChartFactory.createBarChart("Reporte 2", "Cantidad de Vehículos", "Zona", dataSet, PlotOrientation.VERTICAL,true , true, true);
            CategoryPlot plot = chart.getCategoryPlot();
            plot.setRangeGridlinePaint(Color.BLACK);

            BarRenderer renderer= (BarRenderer) plot.getRenderer();
            renderer.setDrawBarOutline(false);
            //Dar color a cada barra
            GradientPaint gp0= new GradientPaint(0.0f,0.0f,Color.MAGENTA,0.0f,0.0f,new Color(0,0,64));
            renderer.setSeriesPaint(0,gp0);

            writeChartToPDF(chart, 800, 500, filename);
            this.dispose();
 
        } catch (Exception e) {
        }

    }//GEN-LAST:event_btnGuardarActionPerformed

//    /**
//     * @param args the command line arguments
//     */
//    public static void main(String args[]) {
//        /* Set the Nimbus look and feel */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
//         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(Reporte2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(Reporte2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(Reporte2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(Reporte2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /* Create and display the form */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            public void run() {
//                new Reporte2().setVisible(true);
//            }
//        });
//    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnGenerar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JComboBox cmbDia;
    private javax.swing.JComboBox cmbRango;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    // End of variables declaration//GEN-END:variables

    private void writeChartToPDF(JFreeChart chart, int width, int height, String fileName) {
        PdfWriter writer = null;
//        Document document = new Document();
        Document document = new Document(PageSize.LETTER.rotate());

        try {
            writer = PdfWriter.getInstance(document, new FileOutputStream(fileName+".pdf"));
            document.open();
            PdfContentByte contentByte = writer.getDirectContent();
            PdfTemplate template = contentByte.createTemplate(width, height);
            Graphics2D graphics2d = template.createGraphics(width, height, new DefaultFontMapper());
            Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width, height);
            chart.draw(graphics2d, rectangle2d);
            graphics2d.dispose();
            contentByte.addTemplate(template, 0, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        document.close();
    }
//
//    private void inicializar() {
//         this.reportesPropiedades = new PropiedadesReportes().getProperties();
//        port = this.reportesPropiedades.getProperty("port");
//        server = this.reportesPropiedades.getProperty("server");
//    }

}
